const path = require('path');

const Koa = require('koa');

const websocket = require('koa-websocket');

const { koaBody } = require('koa-body');

const koaStatic = require('koa-static');

const cors = require('@koa/cors');

const router = require('../router');

const wsRouter = require('../router/ws');

const errHandler = require('./errHandler');

const successHandler = require('./successHandler');

const app = websocket(new Koa());

app.use(
  cors({
    origin: '*', // 允许所有域名的请求
    allowMethods: ['GET', 'POST', 'PUT', 'DELETE'], // 允许的请求方法
    allowHeaders: ['Content-Type', 'Authorization'], // 允许的请求头
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'], // 允许前端获取的响应头
    maxAge: 5, // 预检请求的有效期，单位为秒
    credentials: true, // 是否允许发送Cookie
  })
);

app.use(
  koaBody({
    multipart: true,
    formidable: {
      uploadDir: path.join(__dirname, '../upload'),
      keepExtensions: true,
    },
    parsedMethods: ['POST', 'PUT', 'PATCH', 'DELETE'],
  })
);

app.use(koaStatic(path.join(__dirname, '../upload')));

app.use(router.routes()).use(router.allowedMethods());

app.ws.use(wsRouter.routes()).use(wsRouter.allowedMethods());

app.on('error', errHandler);

app.on('success', successHandler);

module.exports = app;
